package com.demo.controller;

import com.demo.model.User;
import com.demo.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/redis")
@Slf4j
public class RedisTestController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedisUtil redisUtil;

    //k-v都是字符串
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("/set")
    @ResponseBody
    public String set() {
        log.info("存入redis值");
        //设置带有过期时间的key
        stringRedisTemplate.opsForValue().set("k1", "Hello", 20, TimeUnit.SECONDS);
        return "seccess";
    }

    @GetMapping("/get")
    @ResponseBody
    public String get() {
        return stringRedisTemplate.opsForValue().get("k1");
    }

    @PostMapping("/putKey")
    @ResponseBody
    public String putKey(@RequestBody User user) {
        if (StringUtils.isEmpty(user)) {
            return "key must not empty";
        } else {
            if (redisUtil.set("user", user, 300)) {
                return "success";
            }
        }
        return "fail";
    }

    @PostMapping("/getKey")
    @ResponseBody
    public String getKey(String key) {
        if (StringUtils.isEmpty(key)) {
            return "key must not empty";
        } else {
            User user = (User) redisUtil.get(key);
            return user.toString();
        }
    }

}
